from flask import Flask, render_template
from settings import Config, db
from models import User, Store, Product, Order, OrderItem
from datetime import datetime
from sqlalchemy import text

# 初始化Flask应用
app = Flask(__name__)
# 加载配置
app.config.from_object(Config)
# 初始化数据库
db.init_app(app)

# 创建数据库表（首次运行时需要）
with app.app_context():
    db.drop_all()
    db.create_all()
    # 可选：执行初始化脚本（如果需要从schema.sql导入初始数据）
    with open('schema.sql', 'r', encoding='utf-8') as f:
        sql_script = f.read()
        for statement in sql_script.split(';'):
            if statement.strip():
                db.session.execute(text(statement))
        db.session.commit()

# 路由1：访问单个订单小票 /order/<order_id>
@app.route('/order/<int:order_id>')
def show_order(order_id):
    # 查询订单信息（不存在则返回404）
    order = Order.query.get_or_404(order_id)
    # 查询关联的店铺信息
    store = Store.query.get(order.store_id)
    # 查询订单项（包含关联的产品信息）
    order_items = OrderItem.query.filter_by(order_id=order_id).all()
    
    # 整理产品数据
    products = []
    for item in order_items:
        products.append({
            'name': item.product.name,
            'spec': item.product.spec,
            'price': item.product.price,
            'quantity': item.quantity,
            'image_path': item.product.image_path
        })
    
    # 计算总价和总份数
    total_price = sum(p['price'] * p['quantity'] for p in products)
    total_quantity = sum(p['quantity'] for p in products)
    
    # 渲染订单小票模板
    return render_template(
        "dogfights-receipt.html",
        # 订单基本信息
        order_id=order.order_id,
        order_time=order.order_time.strftime('%Y-%m-%d %H:%M:%S'),
        pickup_number=order.pickup_number,
        payment_method=order.payment_method,
        dining_type=order.dining_type,
        dining_time=order.dining_time,
        # 店铺信息
        shop_name=store.store_name,
        shop_address=store.store_address,
        # 产品信息
        products=products,
        total_price=total_price,
        total_quantity=total_quantity
    )

# 路由2：访问用户所有订单 /user/<user_id>
@app.route('/user/<int:user_id>')
def user_orders(user_id):
    # 查询用户信息（不存在则返回404）
    user = User.query.get_or_404(user_id)
    # 查询用户所有订单（按下单时间倒序）
    orders = Order.query.filter_by(user_id=user_id).order_by(Order.order_time.desc()).all()
    
    # 整理每个订单的详细信息
    order_list = []
    for order in orders:
        # 查询店铺信息
        store = Store.query.get(order.store_id)
        # 查询订单项
        order_items = OrderItem.query.filter_by(order_id=order.id).all()
        
        # 计算订单总价和总份数
        total_price = sum(item.product.price * item.quantity for item in order_items)
        total_quantity = sum(item.quantity for item in order_items)
        
        # 整理产品简略信息
        products = [{
            'name': item.product.name,
            'quantity': item.quantity
        } for item in order_items]
        
        order_list.append({
            'order_id': order.id,  # 用于跳转的订单ID
            'order_number': order.order_id,  # 显示的订单编号
            'order_time': order.order_time.strftime('%Y-%m-%d %H:%M:%S'),
            'store_name': store.store_name,
            'total_price': total_price,
            'total_quantity': total_quantity,
            'products': products
        })
    
    # 渲染用户订单列表模板
    return render_template(
        "user_orders.html",
        user=user,
        order_list=order_list
    )

if __name__ == "__main__":
    # 运行应用
    app.run(debug=True, port=5011)